/*
 * DocReaderStream.cpp
 *
 *  Created on: 2010-11-22
 *      Author: LiuShiWei
 */
#include <iostream>
#include "DocReaderStream.h"
#include "../antiword/main_u.cpp"
DocReaderStream::DocReaderStream(shared_ptr<ZLInputStream> base, size_t maxSize) :
	myBase(base), myBuffer(0), mySize(maxSize) {
}
DocReaderStream::DocReaderStream(const ZLFile &file) :
	myBase(0), myBuffer(0), mySize(file.size()), path(file.path()) {

}
DocReaderStream::~DocReaderStream() {
	close();
}

bool DocReaderStream::open() {
#ifdef DEBUG
std::cout<< __FILE__ <<":"<< __LINE__ << "["<<__FUNCTION__<<"]" <<"\n";
#endif
	myBuffer = new char[mySize];
	memset (myBuffer,0,mySize);
	char *args[2];
	args[0] = "./antiword";
	args[1] = (char *) path.c_str();
	antiword(2, (char**) args, myBuffer);
	//	HtmlTextOnlyReader reader(myBuffer, mySize);
	//	reader.readDocument(*myBase);
	std::string context(myBuffer);
#ifdef DEBUG
std::cout<< __FILE__ <<":"<< __LINE__ << "["<<__FUNCTION__<<"]" <<myBuffer << "\n";
#endif
		mySize = context.size();
		myOffset = 0;
	//	myBase->close();
	return true;
}

size_t DocReaderStream::read(char *buffer, size_t maxSize) {
	maxSize = min(maxSize, mySize - myOffset);
		if (buffer != 0) {
			memcpy(buffer, myBuffer, maxSize);
		}
		myOffset += maxSize;
	return maxSize;
}

void DocReaderStream::close() {
	if (myBuffer != 0) {
		delete[] myBuffer;
		myBuffer = 0;
	}
}

void DocReaderStream::seek(int offset, bool absoluteOffset) {
	if (!absoluteOffset) {
		offset += myOffset;
	}
	myOffset = min(mySize, (size_t)max(0, offset));
}

size_t DocReaderStream::offset() const {
	return myOffset;
}

size_t DocReaderStream::sizeOfOpened() {
	return mySize;
}
